package com.common.controller;

import com.common.enums.ApiResult;
import com.common.exception.ErrorException;
import com.common.model.SupperModel;
import com.common.service.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

public class Controller<I, S extends BaseService, M extends SupperModel<I>> {

    @Autowired
    protected S service;

    @GetMapping("/searchAll")
    public ApiResult searchAll() {
        return ApiResult.success(service.searchAll());
    }

    @GetMapping("/getById")
    public ApiResult getById(@RequestParam I id) {
        return ApiResult.success(service.getById(id));
    }

    @PostMapping("/update")
    public ApiResult update(@RequestBody M model) {
        Object id = model.getId();
        if (ObjectUtils.isEmpty(id)) {
            throw new ErrorException("主键id不能为空");
        }
        return ApiResult.success(service.update(model));
    }

    @PostMapping("/delete")
    public ApiResult delete(@RequestBody M model) {
        if (ObjectUtils.isEmpty(model.getId())){
            throw new ErrorException("主键信息不能为空！");
        }
        return ApiResult.success(service.delete(model.getId()));
    }

    @PostMapping("/add")
    public ApiResult add(@RequestBody M model) {
        return ApiResult.success(service.add(model));
    }

    @GetMapping("/searchPage")
    public ApiResult searchPage(@RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "10") int limit,
                                @RequestParam(required = false) Map<String,Object> params) {
        return ApiResult.success(service.searchPage(page, limit));
    }
}